package com.hantanger.weblog.util;

import com.hantanger.weblog.model.User;

/**
 * 获取和设置访问者信息的辅助类
 * @author lys
 *
 */
public final class UserHelper {

	private static ThreadLocal<UserInfo> userInfoContext = new ThreadLocal<UserInfo>();

	private static UserInfo getUserInfo() {
		return userInfoContext.get();
	}

	public static void setUserInfo(User user, String visitorIP) {
		UserInfo userInfo = new UserInfo();
		userInfo.setCurrentUser(user);
		userInfo.setVisitorIP(visitorIP);
		userInfoContext.set(userInfo);
	}
	
	/**
	 * 是否为管理员
	 * @return
	 */
	public static boolean isAdmin() {
		return getUserInfo().isAdmin();
	}
	
	/**
	 * 是否线上环境
	 * @return
	 */
	public static boolean isOnlineEnv(){
		return !"127.0.0.1".equals(UserHelper.getVisitorIp());
	}

	/**
	 * 访问者的用户信息
	 * @return
	 */
	public static User getCurrentUser() {
		return getUserInfo().getCurrentUser();
	}
	
	/**
	 * 访问者的ip
	 * @return
	 */
	public static String getVisitorIp(){
		return getUserInfo().getVisitorIP();
	}
	
	/**
	 * 是否已登录
	 * @return
	 */
	public static boolean isLogined(){
		return getUserInfo().getCurrentUser() != null;
	}
}

class UserInfo {

	private User currentUser;

	private String visitorIP;
	
	public User getCurrentUser() {
		return currentUser;
	}

	public void setCurrentUser(User currentUser) {
		this.currentUser = currentUser;
	}

	public String getVisitorIP() {
		return visitorIP;
	}

	public void setVisitorIP(String visitorIP) {
		this.visitorIP = visitorIP;
	}

	public boolean isAdmin() {
		if(currentUser == null){
			return false;
		}
		return currentUser.getPrivilege() == User.PRIVILEGE_ADMIN;
	}

}